package com.xuecheng.teaching.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.CommentStatusDto;
import com.xuecheng.commons.model.dto.CourseCommentDto;
import com.xuecheng.commons.model.dto.PageRequest;
import com.xuecheng.commons.model.vo.*;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.api.ContentClient;
import com.xuecheng.system.api.SystemClient;
import com.xuecheng.teaching.domain.CommentReply;
import com.xuecheng.teaching.domain.CourseComment;
import com.xuecheng.teaching.mapper.CourseCommentMapper;
import com.xuecheng.teaching.service.CommentReplyService;
import com.xuecheng.teaching.service.CourseCommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exception.BusinessException;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-08-13
 */
@Service
public class CourseCommentServiceImpl extends ServiceImpl<CourseCommentMapper, CourseComment> implements CourseCommentService {

    @Autowired
    private SystemClient systemClient;

    @Autowired
    private ContentClient contentClient;

    @Autowired
    private CommentReplyService commentReplyService;

    //门户详情页----评论课程
    @Override
    public ResponseResult courseComment(CourseCommentDto dto) {
        //1. 判断用户是否登录
        Long userId = AuthInfoHolder.getUserId();
        if (ObjectUtil.isEmpty(userId)){
            throw new BusinessException(ErrorCode.NOTLOGIN);
        }
        //2. 调用feign查询用户信息
        ResponseResult<UserVo> systemResponseResult = systemClient.phone();
        //2-1 判断
        if (systemResponseResult.getCode()!=0) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        //2-2 取出信息
        UserVo userVo = systemResponseResult.getData();

        //3. 调用feign查询课程发布信息
        ResponseResult<CoursePubVo> contentResponseResult = contentClient.findById(dto.getTargetId().longValue());
        //3-1 判断
        if (contentResponseResult.getCode()!=0) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        //3-2 取出信息
        CoursePubVo coursePubVo = contentResponseResult.getData();

        //4. dto -> entity
        CourseComment courseComment = BeanHelper.copyProperties(dto, CourseComment.class);
        //4. 补全信息
        courseComment.setBelongTo(coursePubVo.getCompanyId());   //设置所属机构id
        courseComment.setComeFrom(coursePubVo.getName());    //设置所属课程名
        courseComment.setCommentDate(DateUtil.now());   //设置评论创建时间

        courseComment.setNickName(userVo.getName());    //当前用户昵称

        courseComment.setTargetName(coursePubVo.getName());  //设置所属课程名
        courseComment.setUserId(userId);    //当前用户id
        courseComment.setUserName(userVo.getName());    //当前用户名
        //4. 存入mysql
        this.save(courseComment);
        //5. 主键返回 存commentId
        courseComment.setCommentId(courseComment.getId().intValue());
        this.updateById(courseComment);
        //6. entity -> vo
        CourseCommentVo vo = BeanHelper.copyProperties(courseComment, CourseCommentVo.class);

        ////6. 因为mp的主键返回设置commentId
        //vo.setCommentId(courseComment.getId().intValue());
        //5. 返回
        return ResponseResult.okResult(vo);
    }

    //门户详情页----课程评论列表
    @Override
    public ResponseResult pageCourseComment(PageRequest request, CommentStatusDto dto) {
        //0.获取基础信息
        Long companyId = AuthInfoHolder.getCompanyId();
        //1.参数校验
        Integer pageNum = request.getPageNo();
        Integer pageSize = request.getPageSize();
        if (ObjectUtil.isEmpty(pageNum)) {
            pageNum = 1;
        }
        if (ObjectUtil.isEmpty(pageSize)) {
            pageSize = 10;
        }
        //2.开启分页查询
        Page<CourseComment> page = new Page<>(pageNum,pageSize);
        //3. 设置条件
        LambdaQueryWrapper<CourseComment> qw1 = new LambdaQueryWrapper<>();
        qw1.eq(ObjectUtil.isNotEmpty(companyId),CourseComment::getBelongTo, companyId);  //设置当前企业id
        qw1.eq(ObjectUtil.isNotEmpty(dto.getTargetId()), CourseComment::getTargetId,dto.getTargetId());
        //设置模糊查询条件
        //qw1.like(StrUtil.isNotBlank(courseName),CourseComment::getTargetName,courseName);
        //设置排序,默认按照时间倒序排
        qw1.orderByDesc(CourseComment::getCommentDate);
        //设置好 中 差评条件查询
        if (ObjectUtil.isNotEmpty(dto.getLevel())){
            if (dto.getLevel()==1){
                qw1.between(CourseComment::getStarRank,4,5);
            }
            if (dto.getLevel()==0){
                qw1.between(CourseComment::getStarRank,2,3);
            }
            if (dto.getLevel()==-1){
                qw1.between(CourseComment::getStarRank,0,1);
            }
        }

        page = this.page(page, qw1);
        //判断分页是否为空
//        if (ObjectUtil.isEmpty(page.getRecords())){
//            //直接返回
//            return PageResponseResult.okResult();
//        }
        //4. 获取分页数据
        //4-1 总数
        return getPageResponse(page);
    }

    //门户详情页----课程评论统计
    @Override
    public ResponseResult countCourseComment(Integer targetId) {
        //1. 根据id查询所有评论
        LambdaQueryWrapper<CourseComment> qw = new LambdaQueryWrapper<>();
        qw.eq(CourseComment::getTargetId,targetId);
        List<CourseComment> commentList = this.list(qw);
        //2. 获取总数
        Integer total = commentList.size();
        //3. 初始化vo类
        StarRankVo starRankVo = new StarRankVo();
        Integer count = 0;  //设置分数
        Integer starOne = 0;
        Integer starTwo = 0;
        Integer starThree = 0;
        Integer starFour = 0;
        Integer starFive = 0;
        //3. 遍历
        for (CourseComment comment : commentList) {
            switch(comment.getStarRank()){
                //3-1如果为一星
                case 1:
                    starOne++;
                    break;
                case 2:
                    starTwo++;
                    break;
                case 3:
                    starThree++;
                    break;
                case 4:
                    starFour++;
                    break;
                case 5:
                    starFive++;
                    break;
                default:
                    break;
            }
            count += comment.getStarRank();
        }
        //封装到vo
        starRankVo.setStarRank1Nums(starOne);
        starRankVo.setStarRank2Nums(starTwo);
        starRankVo.setStarRank3Nums(starThree);
        starRankVo.setStarRank4Nums(starFour);
        starRankVo.setStarRank5Nums(starFive);
        starRankVo.setTotalCommentNums(total);
        //若总记录为空则,不进行平均数计算
        if (total==0){
            starRankVo.setStarRank("0");
        }else {
            starRankVo.setStarRank(String.valueOf(count/total));
        }
        starRankVo.setTargetId(targetId);
        //返回
        return ResponseResult.okResult(starRankVo);
    }

    //评论信息模糊查询
    @Override
    public ResponseResult pageByName(String courseName) {
        //1.获取基础数据
        Long companyId = AuthInfoHolder.getCompanyId();
        //2.获取基础分页数据
        PageRequest pageRequest = new PageRequest();
        Integer pageNo = pageRequest.getPageNo();
        Integer pageSize = pageRequest.getPageSize();
        //3. 开启分页
        Page<CourseComment> page = new Page<>(pageNo, pageSize);
        //4. 设置条件
        LambdaQueryWrapper<CourseComment> qw = new LambdaQueryWrapper<>();
        qw.eq(ObjectUtil.isNotEmpty(companyId),CourseComment::getBelongTo, companyId);  //设置当前企业id
        //设置模糊查询条件
        qw.like(StrUtil.isNotBlank(courseName),CourseComment::getTargetName,courseName);
        //设置排序,默认按照时间倒序排
        qw.orderByDesc(CourseComment::getCommentDate);
        page = this.page(page, qw);
        //5. 获取分页数据并返回
        return getPageResponse(page);
    }



    //分页结果解析
    private ResponseResult getPageResponse(Page<CourseComment> page) {
        //4-1 总数
        long total = page.getTotal();
        //4-2 遍历
        //创建集合用于存放分页信息
        List<CourseCommentVo> voList = new ArrayList<>();
        for (CourseComment courseComment : page.getRecords()) {
            //4-2-1存入vo
            CourseCommentVo vo = BeanHelper.copyProperties(courseComment, CourseCommentVo.class);
            //4-2-2 判断是否存在回复
            if (vo.getForbidReply() == 1) {
                //若不存在,则直接添加到集合
                voList.add(vo);
            } else {
                //若存在,则查询回复评论列表
                LambdaQueryWrapper<CommentReply> qw2 = new LambdaQueryWrapper<>();
                qw2.eq(CommentReply::getCommentId, vo.getCommentId());
                List<CommentReply> replyList = commentReplyService.list(qw2);
                //判断是否有回复
                if (CollectionUtil.isNotEmpty(replyList)) {
                    vo.setReplyDTOList(replyList.toArray());
                }
                //添加到集合
                voList.add(vo);
            }
        }
        //返回分页评论数据
        return PageResponseResult.okResult(total, voList);
    }
}
